
#include "../../../inc/Ui/GoogleBuzz/GoogleBuzzMenuForm.h"
#include "../../../inc/Ui/WebForm.h"
using namespace Osp::Base;
using namespace Osp::Ui;
using namespace Osp::Ui::Controls;

int GoogleBuzzMenuForm::FormId = -1;

GoogleBuzzMenuForm::GoogleBuzzMenuForm(void)
{
	accessToken = L"";
	refreshToken = L"";
	apiKey = L"AIzaSyDeX3wYvKbCQzJPIcrAF-Ytlj6dWeom5fA";

	pGoogleBuzzNewActivity = null;
	pGoogleBuzzTokenForm = null;
}

GoogleBuzzMenuForm::~GoogleBuzzMenuForm(void)
{
}

bool
GoogleBuzzMenuForm::Initialize()
{
	Form::Construct(L"GoogleBuzzMenuForm");

	return true;
}

result
GoogleBuzzMenuForm::OnInitializing(void)
{
	result r = E_SUCCESS;

	// TODO: Add your initialization code here

	pAddActivityButton = static_cast<Button*>(GetControl(L"IDC_Add_Activity"));
	if (pAddActivityButton != null){
		pAddActivityButton->SetActionId(ID_ADD_ACTIVITY);
		pAddActivityButton->AddActionEventListener(*this);
	}

	pListActivityButton = static_cast<Button*>(GetControl(L"IDC_ListActivity"));
	if (pListActivityButton != null){
		pListActivityButton->SetActionId(ID_LIST_ACTIVITY);
		pListActivityButton->AddActionEventListener(*this);
	}

	return r;
}

void GoogleBuzzMenuForm::OnUserEventReceivedN(RequestId requestId, Osp::Base::Collection::IList* pArgs){
	switch(requestId){
		case REQUEST_GET_TOKEN_CANCEL:
			ReturnWebForm();
			break;

		case REQUEST_GET_TOKEN_OK:
			ContinueAfterGetTokenN(pArgs);
			break;

		case REQUEST_ADD_ACTIVITY_OK:
			AddActivityN(pArgs);
			break;

		case REQUEST_ADD_ACTIVITY_CANCEL:
			AddActivityCancel();
			break;

		default:
			if (pArgs != null){
				pArgs->RemoveAll(true);
				delete pArgs;
			}
	}
}

void GoogleBuzzMenuForm::ContinueAfterGetTokenN(IList *pListArgs){
	//Frame *pFrame = static_cast<Frame*>(this->GetParent());
	//pFrame->RemoveControl(*pGoogleBuzzTokenForm);

	String *pAccessToken = (String*)pListArgs->GetAt(0);
	String *pRefreshToken = (String*)pListArgs->GetAt(1);

	accessToken = *pAccessToken;
	refreshToken = *pRefreshToken;

	pListArgs->RemoveAll(true);
	delete pListArgs;
}

void GoogleBuzzMenuForm::ReturnWebForm(){
	Frame *pFrame = FormManager::GetFrame();
	pFrame->RemoveControl(*pGoogleBuzzTokenForm);
	FormManager *pFrameManager = null;
	FormManager::GetInstance(pFrameManager);
	pFrameManager->SetCurrentForm(WebForm::GetFormId());
}

result
GoogleBuzzMenuForm::OnTerminating(void)
{
	result r = E_SUCCESS;

	// TODO: Add your termination code here
	return r;
}

void GoogleBuzzMenuForm::OnActionPerformed(const Control &source, int actionId){
	switch (actionId){
	case ID_ADD_ACTIVITY:
		ProcessAddActivity();
		break;

	case ID_LIST_ACTIVITY:
		ProcessShowListActivity();
		break;
	}
}

void GoogleBuzzMenuForm::ProcessAddActivity(){
	pGoogleBuzzNewActivity = new GoogleBuzzNewActivity();
	pGoogleBuzzNewActivity->Initialize();
	Frame *pFrame = FormManager::GetFrame();
	pFrame->AddControl(*pGoogleBuzzNewActivity);
	pFrame->SetCurrentForm(*pGoogleBuzzNewActivity);
	pFrame->RequestRedraw(true);
}

void GoogleBuzzMenuForm::AddActivityN(IList *pListArgs){
	Frame *pFrame = FormManager::GetFrame();
	pFrame->RemoveControl(*pGoogleBuzzNewActivity);

	String *pTitle = (String*)pListArgs->GetAt(0);
	String *pContent = (String*)pListArgs->GetAt(1);
	String utf8Title = L"";
	String utf8Content = L"";

	result r = MyUtil::StringToUTF8String(*pTitle, utf8Title);
	if (IsFailed(r)){
		utf8Title = *pTitle;
	}

	r = MyUtil::StringToUTF8String(*pContent, utf8Content);
	if (IsFailed(r)){
		utf8Content = *pContent;
	}
	pListArgs->RemoveAll(true);
	delete pListArgs;

	String url = L"https://www.googleapis.com/buzz/v1/activities/@me/@self?key=AIzaSyDeX3wYvKbCQzJPIcrAF-Ytlj6dWeom5fA&alt=json&oauth_token=";
	url.Append(accessToken);
	HttpHeader *pHeader = new HttpHeader();

	pHeader->AddField(String(L"Content-Type"), String(L"application/json"));

	JsonObject data;

	JsonString jsonString;
	jsonString.setValue(L"note");

	data.insertValue(L"type", &jsonString);
	jsonString.setValue(utf8Content);
	data.insertValue(L"content", &jsonString);

	jsonString.setValue(utf8Title);
	data.insertValue(L"title", &jsonString);

	JsonObject object;
	object.insertValue(L"object", &data);

	float longitude = 0;
	float latitude = 0;
	CurrentLocationService::getInstance()->GetCurrentLocation(longitude, latitude);
	String temp = L"";
	temp.Append(latitude);
	temp.Append(' ');
	temp.Append(longitude);
	jsonString.setValue(temp);
	object.insertValue(L"geocode", &jsonString);
	JsonObject objectData;
	objectData.insertValue(L"data", &object);

	String strJsonString = objectData.toJsonString();


	ByteBuffer *pBody = null;
	pBody = Utility::StringUtil::StringToUtf8N(strJsonString);
	status = ID_ADD_ACTIVITY;
	Download(url, pBody, pHeader, NET_HTTP_METHOD_POST);
}

void GoogleBuzzMenuForm::AddActivityCancel(){

}

void GoogleBuzzMenuForm::ProcessShowListActivity(){
	status = ID_LIST_ACTIVITY;
	String url = L"https://www.googleapis.com/buzz/v1/activities/search?key=";
	url.Append(apiKey);
	float latitude = 0;
	float longitude = 0;
	CurrentLocationService *locationService = CurrentLocationService::getInstance();
	locationService->GetCurrentLocation(longitude, latitude);
	url.Append(L"&lat="); url.Append(latitude);
	url.Append(L"&lon="); url.Append(longitude);
	url.Append(L"&radius=100000&alt=json");
	//String url = L"https://www.googleapis.com/buzz/v1/activities/@all/@public";
	HttpHeader *pHeader = new HttpHeader();

	pHeader->AddField(String(L"Content-Type"), String(L"application/json"));
	Download(url, null, pHeader, NET_HTTP_METHOD_GET);
}

void GoogleBuzzMenuForm::ShowListActivity(HttpSession &httpSession, HttpTransaction &httpTransaction){
	HttpResponse* pResponse = httpTransaction.GetResponse();
	NetHttpStatusCode statusCode = pResponse->GetStatusCode();

	ByteBuffer* pBody = pResponse->ReadBodyN();
	int limit = pBody->GetLimit();
	pBody->Flip(POSITION_TO_ZERO);
	pBody->SetLimit(limit);

	if (statusCode != 200) {
		AppLog("Failed");
	}

	pBody->SetPosition(0);

	JsonObject jsonObject;

	JsonReader reader;
	reader.read(pBody, jsonObject);

	JsonObject *dataJsonObject = null;
	dataJsonObject = (JsonObject*) jsonObject.getValueN(L"data");
	JsonArray *itemsJsonArray = null;
	itemsJsonArray = (JsonArray*) dataJsonObject->getValueN(L"items");
	delete dataJsonObject;
	int count = itemsJsonArray->getSize();

	JsonObject *actorJsonObject = null;
	JsonString *actorPictureJsonString = null;
	JsonString *titleJsonString = null;
	JsonString *actorNameJsonString = null;
	JsonString *addressJsonString = null;
	JsonString *placeNameJsonString = null;
	JsonString *actorPositionJsonString = null;

	String latlngString = L"";
	String utf8PlaceNameString = L"";
	String utf8AddressString = L"";
	String utf8TitleString = L"";

	for (int i = 0; i < count; i++){
		JsonObject *element = null;
		element = (JsonObject*)itemsJsonArray->getValueN(i);

		titleJsonString = (JsonString*)element->getValueN(L"title");


		actorJsonObject = (JsonObject*)element->getValueN(L"actor");

		actorPictureJsonString = (JsonString*)actorJsonObject->getValueN(L"thumbnailUrl");
		actorNameJsonString = (JsonString*)actorJsonObject->getValueN(L"name");

		addressJsonString = (JsonString*)element->getValueN(L"address");
		placeNameJsonString = (JsonString*)element->getValueN(L"placeName");

		actorPositionJsonString = (JsonString*)element->getValueN(L"geocode");


		latlngString = actorPositionJsonString->getValue();

		float latFloat = Float::GetMinValue();
		float lngFloat = Float::GetMinValue();
		int spaceIndexInt = 0;
		latlngString.IndexOf(' ', 0, spaceIndexInt);
		if (spaceIndexInt != -1){
			String lngString = L"";
			latlngString.SubString(spaceIndexInt, lngString);
			latlngString.Replace(lngString, L"");
			lngString.Trim();
			Float::Parse(lngString, lngFloat);
			Float::Parse(latlngString, latFloat);
		}

		if (placeNameJsonString == null){
			placeNameJsonString = new JsonString();
		}
		if (addressJsonString == null){
			addressJsonString = new JsonString();
		}



		WebController::SetGoogleBuzzMarker(latFloat, lngFloat, actorNameJsonString->getValue(), actorPictureJsonString->getValue(),
				placeNameJsonString->getValue(), addressJsonString->getValue(), titleJsonString->getValue());



		delete actorNameJsonString;
		delete placeNameJsonString;
		delete addressJsonString;
		delete titleJsonString;
		delete actorPictureJsonString;
		delete actorPositionJsonString;
		delete actorJsonObject;
		delete element;
	}

	FormManager *pFormManager = null;
	FormManager::GetInstance(pFormManager);
	pFormManager->SetCurrentForm(WebForm::GetFormId());

	AppLog("Xong rui");
}

void GoogleBuzzMenuForm::Begin(){
	if (accessToken.GetLength() == 0){
		pGoogleBuzzTokenForm = new GoogleBuzzTokenForm();
		pGoogleBuzzTokenForm->Initialize();
		Frame *pFrame = FormManager::GetFrame();
		pFrame->AddControl(*pGoogleBuzzTokenForm);
		pFrame->SetCurrentForm(*pGoogleBuzzTokenForm);
		pFrame->RequestRedraw(true);
		pGoogleBuzzTokenForm->GetTokent();
	}
}

void GoogleBuzzMenuForm::OnLoadingErrorOccurred (LoadingErrorType error, const Osp::Base::String &reason){

	String err = L"";
	Application *pApp = Application::GetInstance();
	pApp->GetAppResource()->GetString(L"IDS_GOOGLEBUZZGETTOKEN_LOADINDERROR", err);

	MessageBox message;
	message.Construct(String(L"Google buzz"), err, MSGBOX_STYLE_OK, 30000);
	int i;
	message.ShowAndWait(i);
}

void GoogleBuzzMenuForm::Download(String url, ByteBuffer *pBody,
		HttpHeader *pHeader, NetHttpMethod method) {
	result r = E_SUCCESS;


	HttpSession *pSession = new HttpSession();
	r = pSession->Construct(NET_HTTP_SESSION_MODE_NORMAL, null, url, null);

	if (IsFailed(r)) {
		AppLog("Googlebuzzform: That bai");
		return;
	}


	HttpTransaction *pTransaction = pSession->OpenTransactionN();
	if (pTransaction == null) {
		AppLog("Googlebuzzform: Can't open transaction");
		return;
	}

	pTransaction->AddHttpTransactionListener(*this);

	HttpRequest *pRequest = pTransaction->GetRequest();
	if (pRequest == null) {
		AppLog("Googlebuzzform: can't get request");
		return;
	}

	HttpHeader *pRequestHeader = pRequest->GetHeader();
	if (pHeader != null){
		IList *lstName = pHeader->GetFieldNamesN();
		int headerCount = lstName->GetCount();
		for (int i = 0; i < headerCount; i++){
			String *keyName = (String*)lstName->GetAt(i);
			IEnumerator *iEnum = pHeader->GetFieldValuesN(*keyName);
			iEnum->MoveNext();
			String *keyValue = (String*)iEnum->GetCurrent();
			pRequestHeader->AddField(*keyName, *keyValue);

		}
		delete lstName;
	}

	r = pRequest->SetUri(url);
	if (IsFailed(r)) {
		AppLog("Googlebuzzform: can't set url");
		return;
	}

	r = pRequest->SetMethod(method);
	if (IsFailed(r)) {
		AppLog("Googlebuzzform: can't set method");
		return;
	}

	if (pBody != null){
		int length = pBody->GetLimit() - 1;
		String lengthAsString = L"";
		lengthAsString.Append(length);
		pBody->SetPosition(0);
		pRequestHeader->AddField("Content-Length", lengthAsString);
		pTransaction->EnableTransactionReadyToWrite();
		pRequest->WriteBody(*pBody);
	}


	r = pTransaction->Submit();

	if (IsFailed(r)) {
		AppLog("Googlebuzzform: can't submit");

	}
//	delete pTransaction;
	if (pBody != null){
		delete pBody;
	}
	if (pHeader != null){
		delete pHeader;
	}
}

void GoogleBuzzMenuForm::OnTransactionReadyToRead(HttpSession &httpSession,
		HttpTransaction &httpTransaction, int availableBodyLen) {
	AppLog("Vao  on transaction ready to read");
	if (status == ID_ADD_ACTIVITY){
		ProcessShowListActivity();
		return;
	}

	if (status == ID_LIST_ACTIVITY){
		ShowListActivity(httpSession, httpTransaction);
		return;
	}

}
